package system.controller;

import cn.hutool.core.io.IoUtil;
import cn.hutool.core.util.StrUtil;
import cn.hutool.json.JSONUtil;
import common.rusult.JSONResult;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.context.support.ClassPathXmlApplicationContext;
import system.entity.SysUser;
import system.service.SysUserService;
import system.service.impl.SysUserServiceImpl;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/**
 * 控制层
 * @author admin
 * 在当前的案例中：
 *  我们把持久层注入业务层的动作交给了spring容器进行管理
 *  但是在业务层中注入控制层的动作，没有做到最优解，就还是通过读取xml文件的形式去操作的，并没有使用相关的注解驱动
 */
public class MainController extends HttpServlet {
    /**
     * 注入业务层实现类
     */
    private SysUserService sysUserService;
    /**
     * 引入spring配置文件
     */
    private static AbstractApplicationContext ac;

    /**
     * 初始化方法，在请求进入后会启动一次，后面请求再进来，就不会走init方法了，
     */
    @Override
    public void init() throws ServletException {
        System.out.println("servlet初始化方法");
        // 只在应用启动时创建一次Spring容器
        ac = new ClassPathXmlApplicationContext("applicationContext.xml.xml");
    }
    @Override
    protected void service(HttpServletRequest request, HttpServletResponse response) throws ServletException, IOException {
        String servletPath = request.getServletPath();
        request.setCharacterEncoding("UTF-8");
        response.setContentType("application/json;charset=utf-8");
        switch(servletPath){
            case "/insertSysUser.do": insertSysUser(request,response);break;
            case "/deleteSysUser.do": deleteSysUser(request,response);break;
        }
    }

    /**
     * 删除系统用户
     * @param request
     * @param response
     */
    private void deleteSysUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        PrintWriter printWriter = response.getWriter();
        sysUserService = ac.getBean("sysUserServiceImpl", SysUserServiceImpl.class);
        String idsParam = request.getParameter("ids");
        List<Integer> ids = StrUtil.split(idsParam, ',')
                .stream()
                .map(Integer::parseInt)
                .collect(Collectors.toList());
        int[] idArray = ids.stream()
                .filter(Objects::nonNull)  // 防止 null 值（可选）
                .mapToInt(Integer::intValue)
                .toArray();
        int result = sysUserService.deleteSysUser(idArray);
        if(result>0){
            printWriter.println(JSONResult.success("删除成功").toJson());
        }else{
            printWriter.println(JSONResult.error(500,"删除失败").toJson());
        }
        printWriter.close();
    }

    /**
     * 新增用户信息
     * @param request
     * @param response
     */
    private void insertSysUser(HttpServletRequest request, HttpServletResponse response) throws IOException {
        sysUserService = ac.getBean("sysUserServiceImpl",SysUserServiceImpl.class);
        String body = IoUtil.readUtf8(request.getInputStream());
        PrintWriter printWriter = response.getWriter();
        SysUser sysUser = JSONUtil.toBean(body,SysUser.class);
        int result = sysUserService.insertSysUser(sysUser);
        if(result>0){
            printWriter.println(JSONResult.success("新增成功").toJson());
        }else{
            printWriter.println(JSONResult.error(500,"新增失败").toJson());
        }
        printWriter.close();
    }
    /**
     * 销毁方法，在应用关闭时执行
     */
    @Override
    public void destroy() {
        System.out.println("servlet销毁方法.....");
        // 关闭Spring容器
        if (ac != null) {
            ac.close();
        }
    }
}